package com.zygh.lz.service.impl;

import cn.hutool.core.net.url.UrlBuilder;
import cn.hutool.core.util.URLUtil;
import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.symmetric.AES;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zygh.lz.dao.SectionMapper;
import com.zygh.lz.dao.SignMapper;
import com.zygh.lz.dao.StaffMapper;
import com.zygh.lz.dao.XareaMapper;
import com.zygh.lz.entity.*;
import com.zygh.lz.entity.changfeng.SignIn;
import com.zygh.lz.entity.changfeng.SignOut;
import com.zygh.lz.stapprove.ResultUtil;
import com.zygh.lz.util.DateUtils;
import com.zygh.lz.vo.ResultBean;
import com.zygh.lz.vo.ResultBeans;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class LongFengService {


    /**
     * 创建顶层任务（支队单位）=====》创建任务分组（大队单位）======》创建任务（岗位）
     */

    @Resource
    private SectionMapper sectionMapper;
    @Resource
    private StaffMapper staffMapper;
    @Resource
    private XareaMapper xareaMapper;
    @Resource
    private SignMapper signMapper;


    //网关地址
    @Value("${long-feng.gateway}")
    private String gateway;
    //用户名密码获取接口访问 token
    @Value("${long-feng.token}")
    private String token;
    //根据登录用户获取机构树

    @Value("${long-feng.tree}")
    private String tree;
    //签到接口描述
    private static String signin = "/ccf-duty/api/signIn";
    //签退接口描述
    private static final String signout = "/ccf-duty/api/signOff";
    //任务组-添加
    private static final String add = "/ccf-duty/dutyGroup/add";
    //任务-添加
    private static final String saveSerTaskInfo = "/ccf-duty/duty/saveSerTaskInfo";
    //获取任务组树
    @Value("${long-feng.task-group-tree}")
    private String taskGroupTree;
    //根据任务组id获取任务信息
    private static String findDutyMessag = "/ccf-duty/duty/findDutyMessag";
    //任务签到装备绑定接口
    private static String signWithEmtUrl = "/ccf-duty/api/signWithEmt";

    @Value("${long-feng.sersigninrecord}")
    private String sersigninrecord;
    private static final String KEY_ALGORITHM = "AES";
    private static final String encodeKey = "ccfxccfxccfxccfx";
    private static final String rawPassword = "1qaz!QAZ";
    private static final String TOKEN_TYPE = "bearer";

    //密码加密
    private static String encryptUtil() {
        AES aes = new AES(Mode.CBC, Padding.ZeroPadding, new SecretKeySpec(encodeKey.getBytes(), KEY_ALGORITHM),
                new IvParameterSpec(encodeKey.getBytes()));
        return aes.encryptBase64(rawPassword.getBytes());
    }

    static String key = "mysql123@whpd027";
    static String key1 = "whpd027#mysql123";

    public static void encrypt() {
        AES aes = new AES(Mode.CBC, Padding.ZeroPadding, key.getBytes(), key1.getBytes());

    }

    //获取token   .header("Authorization", "Basic Y2NmeDpjY2Z4")
    public String getToken() {
        Map<String, Object> param = new HashMap<>();
        param.put("username", "ccf001");
        param.put("password", encryptUtil());
        param.put("scope", "server");
        String result = HttpRequest.post(gateway + token)
                .header("Content-Type", "application/x-www-form-urlencoded")
                .header("Authorization", "Basic Y2NmeDpjY2Z4")
                .header("TENANT-ID", "1")
                .form(param)
                .execute().body();
        log.info("gateway: " + gateway + token);
        JSONObject jsonObject = JSONObject.parseObject(result);
        log.info(jsonObject.toString());
        return jsonObject.get("access_token").toString();
    }

    //根据登录用户获取机构树
    public JSONArray getTree() {
        String token = getToken();
        String result = HttpRequest.get(gateway + tree)
                .header("Content-Type", "application/x-www-form-urlencoded")
                .header("Authorization", TOKEN_TYPE + token)
                .header("TENANT-ID", "1")
                .execute().body();
        log.info("根据登录用户获取机构树：" + result);
        return JSON.parseObject(result).getJSONArray("data");
    }

    public JSONObject getSign(Integer current, Integer size, String beginDateTime, String endDateTime, String policeName, String policeCode, Integer onlineStatus, List<String> groupIds, List<String> deptIds) {
        StringBuilder param = new StringBuilder();
        if (current == null) {
            current = 1;
        }
        if (size == null) {
            size = 10;
        }
        param.append("current=").append(current);
        param.append("&size=").append(size);
        if (!org.springframework.util.StringUtils.isEmpty(policeName)) {
            param.append("&policeName=").append(policeName);
        }

        if (!org.springframework.util.StringUtils.isEmpty(policeCode)) {
            param.append("&policeCode=").append(policeCode);
        }

        if (!org.springframework.util.StringUtils.isEmpty(onlineStatus)) {
            param.append("&onlineStatus=").append(onlineStatus);
        }
        if (org.springframework.util.StringUtils.isEmpty(beginDateTime)) {
            beginDateTime = DateUtils.getDayBegin();
        }

        if (org.springframework.util.StringUtils.isEmpty(endDateTime)) {
            endDateTime = DateUtils.getDayEnd();
        }
        param.append("&beginDateTime=").append(beginDateTime);
        param.append("&endDateTime=").append(endDateTime);

        if (groupIds!=null&&groupIds.size() > 0) {
            for (String groupId : groupIds) {
                param.append("&groupIds=").append(groupId);
            }
        }
        if (deptIds!=null&&deptIds.size() > 0) {
            for (String deptId : deptIds) {
                param.append("&deptIds=").append(deptId);
            }
        } else {
            param.append("&deptIds=410100270000");
        }

        String s = URLUtil.encodeQuery(param.toString());
        log.info(gateway + sersigninrecord + s);
        String token = getToken();
        String result = HttpRequest.get(gateway + sersigninrecord + "?" + s)
                .header("Content-Type", "application/x-www-form-urlencoded")
                .header("Authorization", TOKEN_TYPE + token)
                .header("TENANT-ID", "1")
                .execute().body();
        return JSON.parseObject(result).getObject("data", JSONObject.class);
    }

    //创建任务组
    /*public void creatRwz(Integer id) {
        //String token = getToken();
        //根据父级id 查询部门列表，循环创建任务组
        List<Section> sections = sectionMapper.selectList(Wrappers.<Section>lambdaQuery()
                .eq(Section::getSectionPid, id));
        for (Section section : sections) {
            String simpleUUID = IdUtil.simpleUUID();
            log.info("任务组id" + simpleUUID);
            Rwz rwz = new Rwz();
            if (section.getSectionPid() == 0) {
                rwz.setPid("-1");
            } else {
                Section section1 = sectionMapper.selectById(id);
                rwz.setPid(section1.getRwzid());
            }
            rwz.setTaskgroupId(simpleUUID)
                    .setTaskgroupName(section.getSectionName())
                    .setTaskgroupDesc(section.getSectionName())
                    .setOrderNo(0)
                    .setCreatorId("1")
                    .setUnitCode("410100000000")
                    .setCreateTime(DateUtil.now())
                    .setOperDate(DateUtil.now())
                    .setIfValid(1);
            String paramString = JSON.toJSONString(rwz);
            String result = HttpRequest.post(gateway + add)
                    .header("Content-Type", "application/json")
                    .header("Authorization", TOKEN_TYPE + token)
                    .header("TENANT-ID", "1")
                    .body(paramString)
                    .execute().body();
            log.info("创建任务组：" + result);
            section.setRwzid(simpleUUID);
            System.out.println(JSON.toJSONString(section));
            sectionMapper.updateById(section);

        }
    }*/


    //创建任务
   /* public void creatRw() {
        String token = getToken();
        List<Xarea> xareas = xareaMapper.selectList(Wrappers.<Xarea>lambdaQuery()
                .isNull(Xarea::getRwid).isNotNull(Xarea::getSectionZid));
        for (Xarea xarea : xareas) {
            String simpleUUID = IdUtil.simpleUUID();
            log.info("==任务id" + simpleUUID);
            Section section = sectionMapper.selectOne(Wrappers.<Section>lambdaQuery()
                    .eq(Section::getSysSectionId, xarea.getSectionZid()));
            Rw rw = new Rw();

            //taskgroupIdPath 任务组的物化路径是格式是， 顶级id/下级id/..../当前id
            StringBuffer stringBuffer = new StringBuffer();
            String askgroupIdPath;
            boolean status = true;
            int pid = section.getSysSectionId();
            do {
                Section sections = sectionMapper.selectOne(Wrappers.<Section>lambdaQuery()
                        .eq(Section::getSysSectionId, pid));
                stringBuffer.insert(0, sections.getRwzid() + "/");
                pid = sections.getSectionPid();
                if (sections.getSectionPid() == 0) {

                    status = false;
                }
            } while (status);
            stringBuffer.deleteCharAt(stringBuffer.length() - 1);
            askgroupIdPath = stringBuffer.toString();

            //serTaskInfoUnitList  任务单位是哪些单位可以看到这个任务，
            // 是个字符串（单位ID）数组，我们这边的的单位， 可以通过获取机构树接口插到


            rw.setTaskId(simpleUUID)
                    .setTaskName(xarea.getName())
                    .setTaskgroupId(section.getRwzid())
                    .setTaskDesc(xarea.getBattalion() + xarea.getName())
                    .setBeginDate(xarea.getStartTime())
                    .setEndDate(xarea.getEndTime())
                    .setOndutyTime(xarea.getStartTime())
                    .setOffdutyTime(xarea.getEndTime())
                    .setSerTaskInfoEquList(null)
                    .setSerTaskInfoUnitList(null)
                    .setTaskgroupIdPath(askgroupIdPath)
                    .setAuxiShouldNum(0)
                    .setShouldNum(0)
                    .setIfVisible(1)
                    .setIfValid(1);
            String paramString = JSON.toJSONString(rw);
            String result = HttpRequest.post(gateway + saveSerTaskInfo)
                    .header("Content-Type", "application/json")
                    .header("Authorization", TOKEN_TYPE + token)
                    .header("TENANT-ID", "1")
                    .body(paramString)
                    .execute().body();
            log.info("创建任务：" + result);
            xarea.setRwid(simpleUUID);
            xareaMapper.updateById(xarea);

        }
    }
*/

    /**
     * 签到给长峰科技推送
     */
    public String CFqdpush(Sign sign) {
        Staff staff = staffMapper.selectByPrimaryKey(sign.getStaffid());
        Section section = sectionMapper.selectByPrimaryKey(staff.getSysSectionId());
        Xarea xarea = xareaMapper.selectByPrimaryKey(sign.getAssignmentid());
        String rwid = sign.getRwid();  //市局特殊勤务任务id
        //String rwid = sectionMapper.getRwid(staff.getStaffNum());

        if (StringUtils.isEmpty(rwid)) {
            log.error("无任务id民警：" + staff.getStaffNum());
        }
        SignIn signIn = new SignIn();

        signIn.setPhone(staff.getStaffIdcard())
                .setUserid(staff.getStaffNum())
                .setUsername(staff.getStaffName())
                .setZw(staff.getStaffPost())
                .setZzjgdm(section.getTempid())
                .setQdlat(sign.getGpsx())
                .setQdlng(sign.getGpsy())
                .setRwid(rwid)
                .setSignid(sign.getId());

        return this.sendSignIn(signIn);
    }


    //签到推送  任务签到接口
    public String sendSignIn(SignIn singIn) {
        long l = System.currentTimeMillis();

        String token = getToken();
        Map<String, Object> param = new HashMap<>();
        param.put("userid", singIn.getUserid());
        param.put("phone", singIn.getPhone());
        param.put("username", singIn.getUsername());
        param.put("zzjgdm", singIn.getZzjgdm());
        param.put("zw", singIn.getZw());
        param.put("rwid", singIn.getRwid());
        param.put("qdlat", singIn.getQdlat());
        param.put("qdlng", singIn.getQdlng());
        String paramString = JSON.toJSONString(param);
        String result = HttpRequest.post(gateway + signin)
                .header("Content-Type", "application/json")
                .header("Authorization", TOKEN_TYPE + token)
                .header("TENANT-ID", "1")
                .body(paramString)
                .execute().body();
        log.info("特殊勤务签到入参：" + paramString + singIn.getSignid());
        log.info("签到结果：" + result);
        JSONObject jsonObject = JSONObject.parseObject(result);
        if ("1000".equals(jsonObject.get("code"))) {

            //修改
            String qdid = JSONObject.parseObject(jsonObject.get("qwQdzxb").toString()).get("qdid").toString();
            Sign sign = signMapper.selectById(singIn.getSignid());
            sign.setQdid(qdid).setCfstatus(1);
            signMapper.updateById(sign);

            long s = System.currentTimeMillis();
            log.info("《《《《《《《《《》》》》》》》》》向长峰推送特殊勤务签到数据：" + (s - l) + "毫秒");
            return JSONObject.parseObject(jsonObject.get("qwQdzxb").toString()).get("qdid").toString();
        } else if ("1006".equals(jsonObject.get("code"))) {
            return JSONObject.parseObject(jsonObject.get("qwQdzxb").toString()).get("rwid").toString();
        } else {
            return result;
        }

    }


    //签退推送
    public void sendSignOut(SignOut signOut) {
        String token = getToken();
        Map<String, Object> param = new HashMap<>();
        param.put("userid", signOut.getUserid());
        param.put("qdid", signOut.getQdid());
        param.put("rwid", signOut.getRwid());
        param.put("xxlat", signOut.getXxlat());
        param.put("xxlng", signOut.getXxlng());
        String paramString = JSON.toJSONString(param);
        String result = HttpRequest.post(gateway + signout)
                .header("Content-Type", "application/json")
                .header("Authorization", TOKEN_TYPE + token)
                .header("TENANT-ID", "1")
                .body(paramString)
                .execute().body();
        log.info(signOut.getUserid() + "签退返回结果：" + result);
    }

    public static void main(String[] args) {
        String result = "{\n" +
                "\"code\": \"1000\",\n" +
                "\"message\": \"签到成功\",\n" +
                "\"qwQdzxb\": {\n" +
                "\"qdid\": \"ad5b0********66ff16e13\",\n" +
                "\"userid\": \"106839\",\n" +
                "\"rwid\": \"d627423af********e305db\",\n" +
                "\"qdlat\": null,\n" +
                "\"qdlng\": null,\n" +
                "\"zzjgdm\": \"4101100\",\n" +
                "\"username\": null,\n" +
                "\"zw\": \"10\",\n" +
                "\"zxzt\": 1,\n" +
                "\"qdsj\": \"2022********32:46\",\n" +
                "\"xxsj\": null,\n" +
                "\"xxlat\": null,\n" +
                "\"xxlng\": null,\n" +
                "\"sfzdxx\": null,\n" +
                "\"zhxgsj\": \"202********32:46\"\n" +
                "} }";
        JSONObject jsonObject = JSONObject.parseObject(result);
        Object qwQdzxb = jsonObject.get("qwQdzxb");
        System.out.println(JSONObject.parseObject(jsonObject.get("qwQdzxb").toString()).get("qdid"));

        boolean status = true;
        do {
            System.out.println("111");

        } while (status);

    }


    /**
     * 获取任务组树
     */
    public ResultBeans getTaskGroupTree() {
        String token = getToken();
        String result = HttpRequest.get(gateway + taskGroupTree)
                .header("Content-Type", "application/x-www-form-urlencoded")
                .header("Authorization", TOKEN_TYPE + token)
                .header("TENANT-ID", "1")
                .execute().body();
        JSONObject jsonObject = JSONObject.parseObject(result);
        if ((Integer) jsonObject.get("code") == 0) {
            return ResultUtil.resultBeansSuccess(jsonObject.get("data"));
        }
        log.info("获取任务组树失败：" + result);
        //log.info("根据登录用户获取任务组树：" + result);
        return ResultUtil.resultBeansError(null);
    }

    /**
     * 获取任务组树
     */
    public ResultBean getTaskGroupTreePc() {
        String token = getToken();
        String result = HttpRequest.get(gateway + taskGroupTree)
                .header("Content-Type", "application/x-www-form-urlencoded")
                .header("Authorization", TOKEN_TYPE + token)
                .header("TENANT-ID", "1")
                .execute().body();
        JSONObject jsonObject = JSONObject.parseObject(result);
        if ((Integer) jsonObject.get("code") == 0) {
            return ResultUtil.setOK("success", jsonObject.get("data"));
        }
        log.info("获取任务组树失败：" + result);
        //log.info("根据登录用户获取任务组树：" + result);
        return ResultUtil.setError(500, "获取任务组树失败", null);
    }

    /**
     * 根据任务组id获取任务信息
     *
     * @param dutyMessag
     * @return
     */
    public ResultBeans findDutyMessag(DutyMessag dutyMessag) {
        String token = getToken();
        Map<String, Object> param = new HashMap<>();
        param.put("ifValid", dutyMessag.getIfValid());
        String[] serTaskInfoUnitList = {"410100270000"};  //机构代码，公安交通管理局
        param.put("taskgroupIds", dutyMessag.getTaskgroupIds());   //任务组id集合
        param.put("serTaskInfoUnitList", dutyMessag.getSerTaskInfoUnitList());   //机构代码
        String paramString = JSON.toJSONString(param);
        String result = HttpRequest.post(gateway + findDutyMessag)
                .header("Content-Type", "application/json")
                .header("Authorization", TOKEN_TYPE + token)
                .header("TENANT-ID", "1")
                .body(paramString)
                .execute().body();
        JSONObject jsonObject = JSONObject.parseObject(result);
        if ((Integer) jsonObject.get("code") == 0) {
            return ResultUtil.resultBeansSuccess(jsonObject.get("data"));
        }
        log.info("根据任务组id获取任务信息失败：" + result);
        return ResultUtil.resultBeansError(null);
    }

    /**
     * 特勤任务签到装备绑定
     *
     * @param signWithEmt
     * @return
     */
    public ResultBeans signWithEmt(SignWithEmt signWithEmt) {
        String token = getToken();
        Map<String, Object> param = new HashMap<>();
        param.put("qdid", signWithEmt.getQdid());
        param.put("zbids", signWithEmt.getZbids());
        String paramString = JSON.toJSONString(param);
        String result = HttpRequest.post(gateway + signWithEmtUrl)
                .header("Content-Type", "application/json")
                .header("Authorization", TOKEN_TYPE + token)
                .header("TENANT-ID", "1")
                .body(paramString)
                .execute().body();
        JSONObject jsonObject = JSONObject.parseObject(result);
        if (jsonObject.get("code").equals("2000")) {
            return ResultUtil.resultBeansSuccess(jsonObject.get("qwRyrwsgxdzbbs"));  //绑定装备信息
        }
        log.info("任务签到装备绑定失败：" + result);
        return ResultUtil.resultBeansError("装备绑定失败！");
    }
}
